package it.agm.fanta.activity;


import it.agm.activity.dialog.GenericDialog;
import it.agm.fanta.FantaserviceApp;
import it.agm.fanta.R;
import it.agm.fanta.activity.fragment.FragmentSessionFactory;
import it.agm.fanta.activity.fragment.LoaderFragment;
import it.agm.fanta.adapter.RadioLegaAdapter;
import it.agm.fanta.asynctask.util.SyncUtility;
import it.agm.fanta.constants.Constants;
import it.agm.fanta.exception.ConnectionException;
import it.agm.fanta.model.LegaSquadra;

import java.lang.reflect.Field;

import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewConfiguration;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;


/**
 * Activity di accesso all'App. L'intera applicazione ?? districata in fragment richiamati da questa
 * Activity
 */
public class MainActivity extends Activity {
	private static final String S_HAS_PERMANENT_MENU_KEY = "sHasPermanentMenuKey";
	private DrawerLayout mDrawerLayout;
	private ListView mDrawerList;
	private RadioGroup mDrawerRadioGroup;
	private ActionBarDrawerToggle mDrawerToggle;
	private Intent intent ;
	private CharSequence mDrawerTitle;
	private CharSequence mTitle;
	private String[] navTitles; 
	private ActionBar actionBar;
	public Dialog mdialog;
	
	private String menuItem;
	private int menuItemPosition;
	
	/**
	 * Metodo che si occupa di creare la action
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		FantaserviceApp.setCurrentActivity(this);
		this.actionBar = getActionBar();
		this.mTitle = mDrawerTitle = getTitle();
		this.navTitles = getResources().getStringArray(R.array.navig_array);
		this.mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
		this.mDrawerRadioGroup =new RadioGroup(this);
		this.mDrawerList = (ListView) findViewById(R.id.left_drawer);
		getOverflowMenu();//Necessario per visualizzare le option nella actioBar con icona
		// set a custom shadow that overlays the main content when the drawer
		// opens
		this.mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow,GravityCompat.START);
		this.mDrawerList.setBackgroundColor(getResources().getColor(R.color.white));
		// set up the drawer's list view with items and click listener
		
		this.mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
		//ADVIEW
		 AdView adView = (AdView) this.findViewById(R.id.adView);
		 AdRequest adRequest = new AdRequest.Builder().build();
		 adView.loadAd(adRequest);
		//ADVIEW
		
		for(LegaSquadra lega : FantaserviceApp.leghe){
			RadioLegaAdapter adapter = new RadioLegaAdapter(); 
			mDrawerRadioGroup.addView(adapter.getView(this, lega));
			mDrawerRadioGroup.setBackgroundColor(getResources().getColor(R.color.black_overlay));
			
		}
		if(FantaserviceApp.leghe != null && FantaserviceApp.leghe.size() >0){
			FantaserviceApp.request.setIdlega("" + FantaserviceApp.leghe.get(0).getIdlega());
			FantaserviceApp.request.setGiornataincorso(false);
			FantaserviceApp.lega = FantaserviceApp.leghe.get(0);
			mDrawerRadioGroup.check(mDrawerRadioGroup.getChildAt(0).getId());
			SyncUtility.syncForLega();
		}
		
		this.mDrawerList.addHeaderView(mDrawerRadioGroup);
		
		this.mDrawerList.setAdapter(new ArrayAdapter<String>(this,R.layout.drawer_list_item, this.navTitles));
		// enable ActionBar app icon to behave as action to toggle nav drawer
		actionBar.setDisplayHomeAsUpEnabled(true);
		// ActionBarDrawerToggle ties together the the proper interactions
		// between the sliding drawer and the action bar app icon
		mDrawerToggle = new ActionBarDrawerToggle(this, /* host Activity */
				mDrawerLayout, /* DrawerLayout object */
				R.drawable.ic_drawer ,/* nav drawer image to replace 'Up' caret */
				R.string.drawer_open, /* "open drawer" description for accessibility */
				R.string.drawer_close /* "close drawer" description for accessibility */
		) {
			public void onDrawerClosed(View view) {
				//getActionBar().setTitle(mTitle);
				if(getResources().getText(R.string.action_live).equals(menuItem) ){
					Intent intent = new Intent(FantaserviceApp.currentActivity(), LiveActivity.class);
					startActivity(intent);
					menuItem = (String) getResources().getText(R.string.action_home);
				}	else{
					selectItemByItemText(menuItem,menuItemPosition);
					invalidateOptionsMenu(); // creates call to
				}											// onPrepareOptionsMenu()
			}

			public void onDrawerOpened(View drawerView) {
				//getActionBar().setTitle(mDrawerTitle);
				invalidateOptionsMenu(); // creates call to
											// onPrepareOptionsMenu()
			}
		};
		mDrawerLayout.setDrawerListener(mDrawerToggle);
		
		try {
			Fragment fragment = FragmentSessionFactory.getFragmentById("");
			FragmentManager fragmentManager = getFragmentManager();
			fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
		} catch (ConnectionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		

	}

	@Override
	protected void onResume() {
		selectItemByItemText(menuItem,0);
		invalidateOptionsMenu();
		
	    super.onResume();
	}
	/**
	 * Metodo che gestisce la creazione del menu di options
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.main, menu);
		return super.onCreateOptionsMenu(menu);
	}

	/* Called whenever we call invalidateOptionsMenu() */
	/**
	 * Metodo che gestisce le menu options
	 */
	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		return super.onPrepareOptionsMenu(menu);
	}
	
	/**
	 * Metodo Necessario per visualizzare le option nella actioBar con icona
	 */
	private void getOverflowMenu() {

	    try {
	       ViewConfiguration config = ViewConfiguration.get(this);
	       Field menuKeyField = ViewConfiguration.class.getDeclaredField(S_HAS_PERMANENT_MENU_KEY);
	       if(menuKeyField != null) {
	           menuKeyField.setAccessible(true);
	           menuKeyField.setBoolean(config, false);
	       }
	   } catch (Exception e) {
	       e.printStackTrace();
	   }
	 }
	
	/**
	 * Metodo che gestisce lo switch tra le option del menu dell'actionBar
	 */
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// The action bar home/up action should open or close the drawer.
		// ActionBarDrawerToggle will take care of this.
		if (mDrawerToggle.onOptionsItemSelected(item)) {
			return true;
		}
		// Handle action buttons
//		if(item.getItemId() == R.id.action_logout){
//			App.utente = null;
//			getSharedPreferences(Constants.PREFS_NAME,MODE_PRIVATE).edit()
//	        .putString(Constants.PREF_USERNAME, null)
//	        .putString(Constants.PREF_PASSWORD, null).commit();
//			intent = new Intent(this,LoginActivity.class);
//			startActivity(intent);
//			finish();
//			return true;
//		}else if(item.getItemId() == R.id.action_sync){
//			MenuItem refreshMenuItem = item;
//			//TODO chiamare gli async Task necessari alla sincronizzazione
//			return true;	
//		}else{
//			return super.onOptionsItemSelected(item);
//		}
		switch (item.getItemId()) {
		case R.id.action_logout:
			FantaserviceApp.utente = null;
			getSharedPreferences(Constants.PREFS_NAME,MODE_PRIVATE).edit()
	        .putString(Constants.PREF_USERNAME, null)
	        .putString(Constants.PREF_PASSWORD, null).commit();
			intent = new Intent(this,LoginActivity.class);
			startActivity(intent);
			finish();
			return true;
		case R.id.action_sync:
			MenuItem refreshMenuItem = item;
			SyncUtility.syncForLega();
			//TODO chiamare gli async Task necessari alla sincronizzazione
			return true;
		case R.id.action_info:
			String versionName;
			try {
				versionName = this.getPackageManager().getPackageInfo(this.getPackageName(), 0).versionName;
				new GenericDialog(FantaserviceApp.currentActivity(),this.mTitle +"\n"+ versionName + "\nCreated by AGM\n" ,"Info");
			} catch (NameNotFoundException e) {
				e.printStackTrace();
			}
			
			//TODO chiamare gli async Task necessari alla sincronizzazione
			return true;	
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	/**
	 *  The click listner for ListView in the navigation drawer
	 */
	private class DrawerItemClickListener implements ListView.OnItemClickListener {
	
		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
			TextView textView = (TextView) view;
//			selectItem(position);
			menuItem = "" +textView.getText();
			menuItemPosition = position;
			Fragment fragment = new LoaderFragment();
			FragmentManager fragmentManager = getFragmentManager();
			fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
			mDrawerLayout.closeDrawer(mDrawerList);
//			selectItemByItemText("" +textView.getText(),position);
		}
	}

	/**
	 * Metodo che gestisce lo switch tra le voci di menu della NavigationDrawer
	 * @param position
	 */
	private void selectItemByItemText(String textView,int position) {
		// update the main content by replacing fragments
		Fragment fragment;
		try {
			if(FantaserviceApp.lega == null && (!"".equals(textView) || textView == null)){
//				SyncUtility.syncForLega();
			}else{
				mDrawerList.setItemChecked(position, true);
				
				fragment = FragmentSessionFactory.getFragmentById(textView);
				FragmentManager fragmentManager = getFragmentManager();
				fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
				
			}
		} catch (ConnectionException e) {
			 AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MainActivity.this,R.style.DialogTheme);
				
			 alertDialogBuilder.setTitle("ERROR");
			 alertDialogBuilder.setMessage(e.getMessage());
			 // set positive button: Yes message
			
			 // set negative button: No message
			 alertDialogBuilder.setNegativeButton("Chiudi",new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog,int id) {
						// cancel the alert box and put a Toast to the user
						dialog.cancel();
					}
				});
			 AlertDialog alertDialog = alertDialogBuilder.create();
			 // show alert
			 alertDialog.show();
		}
				
	}


	@Override
	public void setTitle(CharSequence title) {
		mTitle = title ;
		getActionBar().setTitle(mTitle );
	}

	/**
	 * When using the ActionBarDrawerToggle, you must call it during
	 * onPostCreate() and onConfigurationChanged()...
	 */

	@Override
	protected void onPostCreate(Bundle savedInstanceState) {
		super.onPostCreate(savedInstanceState);
		// Sync the toggle state after onRestoreInstanceState has occurred.
		mDrawerToggle.syncState();
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		// Pass any configuration change to the drawer toggls
		mDrawerToggle.onConfigurationChanged(newConfig);
	}

}